import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_learn_vi/src/page/common/common_loading_dialog.dart';
import 'package:get/get.dart';

import '../../../bean/bean_order.dart';
import '../../common/common_nodata_widget.dart';
import 'controller/order_center_controller.dart';

class OrderListPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return OrderListPageState();
  }
}

class OrderListPageState extends State with SingleTickerProviderStateMixin {
  TabController _tabController;

  @override
  void initState() {
    super.initState();
    Get.put(OrderCenterController());
    _tabController = new TabController(length: 3, vsync: this);
    Future.delayed(Duration.zero, () {
      Get.find<OrderCenterController>().onPullRefresh();
    });
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder(
      id: "orderList",
      builder: (OrderCenterController controller) {
        int allCount = controller.allCount;
        int sendCount = controller.sendCount;
        int finishCount = controller.finishCount;
        return Scaffold(
          appBar: AppBar(
            elevation: 0,
            title: Text("订单中心"),
            bottom: TabBar(
              indicatorColor: Colors.red,
              controller: _tabController,
              onTap: (int index) {
                Get.find<OrderCenterController>().onRefresh(index: index);
              },
              tabs: [
                Tab(text: '全部($allCount)'),
                Tab(text: '待收货($sendCount)'),
                Tab(text: '已完成($finishCount)'),
              ],
            ),
          ),
          body: RefreshIndicator(
            onRefresh: () {
              return Get.find<OrderCenterController>().onPullRefresh();
            },
            child: buildAnimatedSwitcher(context, controller),
          ),
        );
      },
    );
  }

  ///AnimatedSwitcher 的基本使用
  AnimatedSwitcher buildAnimatedSwitcher(BuildContext context, OrderCenterController controller) {
    return AnimatedSwitcher(
      //动画执行切换时间
      duration: const Duration(milliseconds: 400),
      //动画构建器 构建指定动画类型
      transitionBuilder: (Widget child, Animation<double> animation) {
        //执行缩放动画
        return FadeTransition(child: child, opacity: animation);
      },

      ///执行动画的子 Widget
      ///只有子 Widget 被切换时才会触发动画
      child: buildMainWidget(controller),
    );
  }

  buildMainWidget(OrderCenterController controller) {
    List<OrderBean> goodsList = controller.orderList;
    bool isLoading = controller.loading;
    if (isLoading) {
      return SizedBox(
        width: double.infinity,
        height: Get.height / 3 * 2,
        child: Center(
          child: LoadingWidget(),
        ),
      );
    }

    if (goodsList.length == 0) {
      return SizedBox(
        width: double.infinity,
        height: Get.height / 3 * 2,
        child: Center(
          child: NoDataWidget(
            text: "暂无兑换记录 点击刷新",
            clickCallBack: () {
              Get.find<OrderCenterController>().onPullRefresh();
            },
          ),
        ),
      );
    }

    int count = goodsList.length;
    if (count > 10) {
      count = count + 1;
    }

    return NotificationListener(
      onNotification: (ScrollNotification notification) {
        //滑动信息的数据封装体
        ScrollMetrics metrics = notification.metrics;
        //当前位置
        double offset = metrics.pixels;
        double maxOfsset = metrics.maxScrollExtent;
        if (offset > maxOfsset / 3 * 2) {
          Get.find<OrderCenterController>().loadingMore();
        }
        return false;
      },
      child: ListView.builder(
        itemCount: count,
        itemBuilder: (BuildContext context, int index) {
          if (index >= goodsList.length) {
            return Container(
              child: Text("已滑动到底部了"),
              height: 66,
              alignment: Alignment.center,
            );
          }
          OrderBean item = goodsList[index];

          int orderStatues = item.orderStatues;
          String orderStatuesStr = "未知";
          Color orderStatuesColor = Colors.grey;
          if (orderStatues == 201) {
            orderStatuesStr = "待取货 ";
            orderStatuesColor = Colors.red[600];
          } else if (orderStatues == 401) {
            orderStatuesStr = "已取货 ";
            orderStatuesColor = Colors.grey;
          } else if (orderStatues == 402) {
            orderStatuesStr = "已取货 ";
            orderStatuesColor = Colors.grey;
          }

          return Container(
            color: Colors.white,
            margin: EdgeInsets.only(top: 10),
            padding: EdgeInsets.only(left: 12, right: 12, top: 12, bottom: 2),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisSize: MainAxisSize.min,
              children: [
                Row(
                  children: [
                    Expanded(
                      child: Text(
                        "订单编号 ${item.orderSn}",
                        style: TextStyle(
                            color: Colors.black,
                            fontSize: 12,
                            fontWeight: FontWeight.w500),
                      ),
                    ),
                    Text(
                      "$orderStatuesStr",
                      style: TextStyle(
                          fontSize: 14,
                          color: orderStatuesColor,
                          fontWeight: FontWeight.w500),
                    )
                  ],
                ),
                SizedBox(height: 10),
                Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    CachedNetworkImage(
                      imageUrl: item.goodsImage,
                      width: 40,
                    ),
                    SizedBox(
                      width: 6,
                    ),
                    Expanded(
                      child: Column(
                        mainAxisSize: MainAxisSize.min,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            item.goodsName,
                            style: TextStyle(fontSize: 14, color: Colors.grey),
                          ),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.end,
                            children: [
                              Text(
                                "单价 ${item.unitNumber} 积分",
                                textAlign: TextAlign.end,
                                style:
                                TextStyle(fontSize: 14, color: Colors.grey),
                              )
                            ],
                          ),
                          SizedBox(
                            height: 6,
                          ),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.end,
                            children: [
                              Text(
                                "订单总价 ${item.orderPrice} 积分",
                                textAlign: TextAlign.end,
                                style:
                                TextStyle(fontSize: 14, color: Colors.grey),
                              )
                            ],
                          )
                        ],
                      ),
                    )
                  ],
                ),
                SizedBox(height: 10),
                Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    Text(
                      "下单时间 ${item.createTime}",
                      textAlign: TextAlign.end,
                      style: TextStyle(fontSize: 14, color: Colors.grey),
                    )
                  ],
                ),
                buildUsedTimeWidget(item),
                Divider(),
                Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    Expanded(
                      child: Text(
                        "取货码 ${item.formatCode}",
                        textAlign: TextAlign.start,
                        style: TextStyle(
                            fontSize: 16,
                            color: Colors.black,
                            fontWeight: FontWeight.w500),
                      ),
                    ),
                    GetBuilder(
                      id: "confirmButton${item.id}",
                      builder: (OrderCenterController controller) {
                        return buildConformButton(
                            controller, orderStatues, item);
                      },
                    )
                  ],
                ),
                SizedBox(
                  height: 6,
                ),
              ],
            ),
          );
        },
      ),
    );
  }

  buildConformButton(OrderCenterController controller, int orderStatues, OrderBean item) {
    if (orderStatues == 401 || orderStatues == 402) {
      return Container();
    }
    if (controller.confiroLoading) {
      return LoadingWidget(
        text: "处理中",
      );
    }
    return GestureDetector(
      onTap: () {
        Get.find<OrderCenterController>().confirm(item);
      },
      child: ClipRRect(
        child: Container(
          padding: EdgeInsets.only(left: 12, right: 12, top: 8, bottom: 8),
          color: Colors.red[900],
          child: Text(
            "确认取货",
            style: TextStyle(
                fontSize: 12, color: Colors.white, fontWeight: FontWeight.w600),
          ),
        ),
        borderRadius: BorderRadius.all(Radius.circular(4)),
      ),
    );
  }

  buildUsedTimeWidget(OrderBean item) {
    if (item.orderStatues != 401 && item.orderStatues != 402) {
      return Container();
    }
    return Container(
      margin: EdgeInsets.only(top: 6),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          Text(
            "取货时间 ${item.confirmTime}",
            textAlign: TextAlign.end,
            style: TextStyle(fontSize: 14, color: Colors.grey),
          )
        ],
      ),
    );
  }
}
